package com.hfzy.ihk.web.calldata.job;

import com.hfzy.ihk.common.core.elasticsearch.EsQueryUtils;
import com.hfzy.ihk.common.util.FileUtils;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.calldata.entity.CallHistory;
import com.hfzy.ihk.web.calldata.biz.CallHistoryBiz;
import com.hfzy.ihk.web.calldata.dao.CallHistoryRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YANFA on 2018/10/24.
 */
@Component
//@Profile("pro")
public class CheckDownRecordFileJob {

    Logger logger = LoggerFactory.getLogger(CheckDownRecordFileJob.class);


    @Value("${aliyun.recordFilePath}")
    public String recordFilePath;
    @Autowired
    CallHistoryBiz callHistoryBiz;

    @Autowired
    CallHistoryRepository callHistoryRepository;

    @Value("${spring.profiles.active}")
    public String profile;
    /**
     * 晚上将白天的的录音文件下载到本地
     */
    @Scheduled(cron = "0 10 01 * * ?")
    public void checkDownRecordFile() {
        logger.info("-------->开始录音下载job");
        Map<String, Object> paramMap = new HashMap<>();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();

        //查近三天的，防止出现，阿里云服务器升级导致，之前没下载成功的情况
        String createStartTime = DateUtils.getStrFormTime("yyyy-MM-dd",DateUtils.addDay(new Date(), -3)) + " 00:00:00";
        String createEndTime = DateUtils.getStrFormTime("yyyy-MM-dd",DateUtils.addDay(new Date(), -1)) + " 23:59:59";

        builder.must(EsQueryUtils.rangeQuery("createTime", createStartTime, null, true, false));


        builder.must(EsQueryUtils.rangeQuery("createTime", null, createEndTime, false, true));

        builder.must(EsQueryUtils.wildcardQuery("recordFileUrl", "*aliyun*"));
        String[] fields = {"sessionId", "recordFileUrl"};
        Page<CallHistory> page = null;
        boolean isDo = true;
        while (isDo){
            try {
                page = callHistoryBiz.queryCallHistoryPageList(builder, null, PageRequest.of(0, 100), new FetchSourceFilter(fields, null));
            } catch (Exception e) {
                logger.error("跑下载录音job 查询ES 异常！！！", e);
            }
            List<CallHistory> callHistoryList = page.getContent();

            if (page != null && StringTools.isNotempty(callHistoryList)) {
                //开始下载，下载完成以后更新Es,
                for (CallHistory callHistory : callHistoryList) {
                    try {
                        String filePath = recordFilePath + callHistory.getSessionId() + ".wav";
                        //这里要加个转换成外网录音地址
                        FileUtils.getRemoteFile(callHistory.getRecordFileUrl(), filePath);

                        String url = FileUtils.getUrlByPath(filePath,profile );
                        Map<String, Object> updateMap = new HashMap<>();
                        updateMap.put("recordFileUrl", url);
                        //更新数据库
                        callHistoryRepository.updateSomeFields(callHistory.getSessionId(), CallHistory.class, updateMap);
                    } catch (IOException e) {
                        logger.error("------->下载阿里云录音文件job 下载失败，sessionId:{}", callHistory.getSessionId(), e);
                    } catch (Exception e1) {
                        logger.error("------->下载阿里云录音文件job 下载失败，sessionId:{}", callHistory.getSessionId(), e1);
                    }
                }
            }else{
                isDo=false;
            }
         }
        logger.info("-------->结束录音下载job");
    }
}
